package com.shulidata.mock.controller.groovy;

import com.alibaba.fastjson.JSON;
import com.shulidata.mock.service.groovy.GroovyManager;
import com.shulidata.mock.service.groovy.GroovyScriptProcessor;
import com.shulidata.mock.utils.GenericException;
import com.shulidata.mock.utils.ParamType;
import com.shulidata.mock.utils.ServiceCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Fyduan on 2016/5/2.
 */
@RestController
public class RestMockController {

    @Autowired
    private GroovyManager groovyManager;

    // @CrossOrigin // - JDK8后方可使用注解,JDK7则使用XML配置<mvc:cros>
    @RequestMapping(value = "/mock")
    public Object ctrlGetMockData(@RequestParam("id") String id,
                                  @RequestParam("paramType") ParamType paramType,
                                  @RequestParam("params") String params) throws GenericException {

        // 获取到api对应的脚本对象
        GroovyScriptProcessor processor = groovyManager.getScriptProcessor(id);
        if (processor == null || !processor.isInitSuccess()) {
            throw new GenericException(ServiceCode.ERR_PARAM, "没有找到对应的MOCK配置或MOCK脚本还没有刷新到执行引擎");
        }
        // 返回mock数据
        return processor.invoke(convParamsToTargetType(paramType, params));
    }

    private Object convParamsToTargetType(ParamType type, String params) throws GenericException {
        if (params == null) return null;
        Object _params;
        switch (type) {
            case LONG: {
                _params = Long.valueOf(params);
                break;
            }
            case INTEGER: {
                _params = Integer.valueOf(params);
                break;
            }
            case STRING: {
                _params = params;
                break;
            }
            case BOOLEAN: {
                _params = Boolean.valueOf(params);
                break;
            }
            case MAP: {
                _params = JSON.parseObject(params);
                break;
            }
            default:
                throw new GenericException(ServiceCode.ERR_PARAM, "未知的模拟参数类型，目前仅支持：LONG/INTEGER/STRING/BOOLEAN/MAP 等几种类型.");
        }

        return _params;
    }

}
